import { URL_KLINE_HISTORY } from "@/comm/api";
import { formatKey, formatTimeAgo } from "@/comm/format";
import { get } from "@/comm/request";
import { sortList } from "@/comm/tooler";
import { uuidCreate } from "@/comm/uuid";
import { defineStore } from "pinia";

interface IState {
    activitys: Array<any>;
    transfers: Array<any>;
    swaps: Array<any>;
    bigAmounts: Array<any>;
    filters: Array<any>;
    eventList: Array<any>;
    chainActivitys: Array<any>;
    lastItem: any;
    minValue: Number;
    maxValue: Number;
    filterType: String;
}

const MAX_ACCOUNT = 500;
const VISIBLE_ACCOUNT = 30;

const MAX_USDT = 100000;

export const useActivity = defineStore("activity", {
    state: (): IState => ({
        lastItem: null,
        activitys: [],
        transfers: [],
        swaps: [],
        bigAmounts: [],
        filters: [],
        minValue: 0,
        maxValue: Number.MAX_VALUE,
        filterType: "",
        eventList: [],
        chainActivitys: []
    }),

    getters: {
        visibleRange(state) {
            // return state.activitys.slice(0, VISIBLE_ACCOUNT);

            let list = [];
            // if (state.filterType == "transfer") {
            //     list = state.transfers;
            // }
            if (!state.filterType) {
                list = state.activitys;
            } else if (state.filterType == "swap") {
                list = state.swaps;
            } else {
                list = state.transfers.filter(item => {
                    return item.action == state.filterType;
                });
            }
            let len = list.length;
            // console.log("總數 len", len);

            let ary = [];
            for (let i = 0; i < len; i++) {
                let item = list[i];
                // if(!state.filterType || state.filterType == item.type){
                if (item.outusdt >= state.minValue && item.outusdt <= state.maxValue) {
                    ary.push(item);
                    // if (ary.length > VISIBLE_ACCOUNT) {
                    //     break;
                    // }
                }
            }
            return ary;
        }
    },
    actions: {
        changeActivitys(val: any) {
            this.activitys = val;
        },
        addFormatList(val: any) {
            if (!val) return;
            // console.log("add item");
            let ary = Array.isArray(val) ? val : [val];
            // ary.sort((a, b) => (a.timestamp > b.timestamp ? -1 : 1));
            ary.forEach(i => {
                if (!i.uuid) {
                    i.uuid = uuidCreate();
                }
                i.ago = formatTimeAgo(i.timestamp);
                // this.activitys.push(i);
                this.addItem(this.activitys, i);
                if (i.type == "swap") {
                    // this.swaps.push(i);
                    this.addItem(this.swaps, i);
                } else {
                    // this.transfers.push(i)
                    this.addItem(this.transfers, i);
                }
            });
            this.sortItem(this.activitys);
            this.sortItem(this.swaps);
            this.sortItem(this.transfers);
        },
        sortItem(list: any[]) {
            //時間從大到小排序
            list.sort((a, b) => (a.timestamp > b.timestamp ? -1 : 1));
            while (list.length > MAX_ACCOUNT) {
                list.pop();
            }
        },
        addItem(list: any[], val: any) {
            list.push(val);
            // list.sort((a, b) => (a.timestamp > b.timestamp ? -1 : 1));
            // list.unshift(val);
            // while (list.length > MAX_ACCOUNT) {
            //     list.pop();
            // }
        },
        pushActivitys(val: any) {
            if (!val) return;
            // if (Array.isArray(val)) {
            //     // console.log(val.length + " START total")
            //     val.forEach((i: any) => {
            //         i.key = uuidCreate();
            //         // i.ago = formatTimeAgo(i.timestamp);
            //     });
            //     this.activitys.push(...val);

            // } else {
            //     val.key = uuidCreate();
            //     // val.ago = formatTimeAgo(val.timestamp);
            //     this.activitys.push(val);
            // }
            this.addFormatList(val);

            // this.activitys.sort((a, b) => (a.timestamp > b.timestamp ? -1 : 1));
            // while(this.activitys.length > MAX_ACCOUNT){
            //     this.activitys.pop();
            // }
            // console.log(this.activitys.length + "total")
            if (!this.lastItem) {
                this.lastItem = this.activitys[0];
            }
        },

        async loadHistory(type: string = "") {
            // this.activitys = [];
            // this.transfers = [];
            // this.swaps = [];

            this.chainActivitys = [];
            // this.bigAmounts = [];
            console.log("----加载历史数据----");
            try {
                //链上活动数据
                let res: any = await get(URL_KLINE_HISTORY, { group: type || "" });
                let aim = res.data.filter((item: any) => {
                    if (item.type == "swap") {
                        return item.outAmount && item.inAmount;
                    }
                    return true;
                });
                sortList(aim, "timestamp");
                this.chainActivitys = aim;
            } catch (e) {
                console.error("jsz", e);
            }

            // try {
            //     await this.loadBigAmount();
            // } catch (e) {
            //     console.error("jsz", e);
            // }

            try {
                //图标交易绘制数据
                let res: any = await get(URL_KLINE_HISTORY, { group: "BIG_AMOUNT:" + (type ? type : "STABLE_CURRENCY") });
                // res.data.forEach((val: any) => {
                //     val.id = uuidCreate();
                // });
                // this.bigAmounts = res.data;
                // console.log("URL_KLINE_HISTORY", res.data)
                this.eventList = res.data || [];
            } catch (e) {
                console.error("jsz", e);
            }
            return;
        },
        async loadBigAmount() {
            //右侧通知数据
            let res: any = await get(URL_KLINE_HISTORY, { group: "BIG_AMOUNT" });
            res.data.forEach((val: any) => {
                val.id = uuidCreate();
            });
            // console.log("loadBigAmount", res.data);
            this.bigAmounts = res.data || [];
        },
        async loadAllActivity() {
            let res: any = await get(URL_KLINE_HISTORY, { group: "all" });
            let aim = res.data.filter((item: any) => {
                if (item.type == "swap") {
                    return item.outAmount && item.inAmount;
                }
                return true;
            });
            this.pushActivitys(aim);
        },
        pushBigAmounts(item: any) {
            item.id = uuidCreate();
            this.bigAmounts.push(item);
        },
        changeRange(val: any) {
            if (Array.isArray(val)) {
                this.minValue = val[0];
                this.maxValue = val[1] || Number.MAX_VALUE;
            } else {
                this.minValue = 0;
                this.maxValue = Number.MAX_VALUE;
            }
        },
        changeFilterType(val: any) {
            this.filterType = val;
        },
        getEventRange(token: string) {
            let list = this.activitys;
            let ary: any[] = [];
            // let token = kline.curCoin.tokenAddress;
            for (let i = 0; i < list.length; i++) {
                let item = list[i];
                if (item.inTokenAddress == token || item.outTokenAddress == token) {
                    if (item.outusdt >= MAX_USDT || item.inusdt >= MAX_USDT) {
                        ary.push(item);
                    }
                }
            }
            console.log("筛选", ary);
            return ary;
        }
    }
});
